<?php

/*
  Lop model dung chung cho cac models khac
  Viet cac function chung nhu List, Update, Delete
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class MYAD_Model extends CI_Model {

    protected $table_name = '';
    protected $monthForSalary;
    protected $table_employeesalaryinfo = 'm_employeesalaryinfo';
    protected $table_employeepitinfo = 'm_employeepitinfo';
    protected $table_timecard = 'timecard';

    function __construct() {
        parent::__construct();
        $this->load->database();
        $this->monthForSalary = $this->getMonthForSalary();
    }

    // all function list database
    function listAll() {
        $query = $this->db->get($this->table_name);
        return $query->result_array();
    }

    // list all data have pagination
    function listAllPagination($number, $offset, $order) {
        $this->db->order_by($order, "desc");
        $query = $this->db->get($this->table_name, $number, $offset);
        return $query->result_array();
    }

    /**
     * @author Thanh NV        
     * @function countAll 
     * @param: strtotime          
     * Output: int
     * @This function return number holiday on month  
     */
    function listAllPaginationID($number, $offset, $order, $name, $id) {
        $this->db->order_by($order, "desc");
        $this->db->where($name, $id);
        $query = $this->db->get($this->table_name, $number, $offset);
        return $query->result_array();
    }

    function listId($id) {
        $this->db->where('id', $id);
        $query = $this->db->get($this->table_name);
        return $query->row_array();
    }

    function listIdName($name, $id) {
        $this->db->where($name, $id);
        $query = $this->db->get($this->table_name);
        return $query->row_array();
    }

    function listSelect($arraySlect) {
        $strSelect = implode(",", $arraySlect);
        $this->db->select($strSelect);
        $query = $this->db->get($this->table_name);
        return $query->result_array();
    }

    function listWhere($arrayWhere) {
        $this->db->where($arrayWhere);
        $query = $this->db->get($this->table_name);
        return $query->result_array();
    }

    function listOption($arraySelector, $arrayWherever, $Limit) {
        $this->db->select($arraySelector);
        $this->db->where($arrayWherever);
        $this->db->limit($Limit);
        $query = $this->db->get($this->table_name);
        return $query->result_array();
    }

    // end all function list database
    //---------------------------------------
    // all function insert database
    function insertData($arrayInsert) {
        $temp = FALSE;
        $this->db->trans_begin();
        $this->db->insert($this->table_name, $arrayInsert);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $temp = FALSE;
        } else {
            $this->db->trans_commit();
            $temp = TRUE;
        }

        return $temp;
    }

    // end all function insert databse
    //.......................................
    // all function update database
    function updateData($arrayUpdate, $id) {
        $temp = FALSE;
        $this->db->trans_begin();
        $this->db->where('id', $id);
        $this->db->update($this->table_name, $arrayUpdate);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $temp = FALSE;
        } else {
            $this->db->trans_commit();
            $temp = TRUE;
        }
        return $temp;
    }

    // end all function update databse
    // all function update database
    function updateDataName($arrayUpdate, $id, $name) {
        $temp = FALSE;
        $this->db->trans_begin();
        $this->db->where($name, $id);
        $this->db->update($this->table_name, $arrayUpdate);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $temp = FALSE;
        } else {
            $this->db->trans_commit();
            $temp = TRUE;
        }
        return $temp;
    }

    // end all function update databse
    //.......................................
    // all function delete database
    function deleteData($name, $id) {
        $temp = FALSE;
        $this->db->trans_begin();
        $this->db->where($name, $id);
        $this->db->delete($this->table_name);
        if ($this->db->trans_status() === FALSE) {
            $this->db->trans_rollback();
            $temp = FALSE;
        } else {
            $this->db->trans_commit();
            $temp = TRUE;
        }
        return $temp;
    }

    // end all function delete databse 
    // count all item
    function count_all() {
        $query = $this->db->get($this->table_name);
        return $query->num_rows();
    }

    /**
     * @author Thanh NV        
     * @function countAll 
     * @param: $name, $id        
     * Output: int
     * @This function return number holiday on month  
     */
    function count_allID($name, $id) {
        $this->db->where($name, $id);
        $query = $this->db->get($this->table_name);
        return $query->num_rows();
    }

    // end count all item
    // function check login user
    function getUser($username, $password) {
        $this->db->where('UserName', $username);
        $this->db->where('Password', $password);
        $query = $this->db->get($this->table_name);
        return $query->row_array();
    }

    /*
     * @author :        Quyet
     * @created:        11/6/2014
     * @Description:    Get pagination
     * @Input :         array data of pagination
     * @Output :        string pagination
     */

    function getPagination($configs = array()) {
        $default = $this->config->item('pagination');

        /* get language pagi */
        $lfirst = $this->lang->line('pagi_first');
        $lLast = $this->lang->line('pagi_last');
        $lNext = $this->lang->line('pagi_next');
        $lPrev = $this->lang->line('pagi_prev');

        /* set value for label (first, last, next, prev) pagination */
        $first = empty($lfirst) ? $default['first_link'] : $lfirst;
        $last = empty($lLast) ? $default['last_link'] : $lLast;
        $next = empty($lNext) ? $default['next_link'] : $lNext;
        $prev = empty($lPrev) ? $default['prev_link'] : $lPrev;

        $config = array();
        foreach ($default as $key => $item) {
            switch ($key) {
                case 'first_link':
                    $config[$key] = isset($configs[$key]) ? $configs[$key] : $first;
                    break;
                case 'last_link':
                    $config[$key] = isset($configs[$key]) ? $configs[$key] : $last;
                    break;
                case 'next_link':
                    $config[$key] = isset($configs[$key]) ? $configs[$key] : $next;
                    break;
                case 'prev_link':
                    $config[$key] = isset($configs[$key]) ? $configs[$key] : $prev;
                    break;
                default:
                    $config[$key] = isset($configs[$key]) ? $configs[$key] : $default[$key];
                    break;
            }
        }
        $this->pagination->initialize($config);
        return $this->pagination->create_links();
    }

    /*
     * @author :        Quyet
     * @created:        11/6/2014
     * @Description:    Get month for salary caculator
     * @Input :         Null
     * @Output :        (date) uninx
     */

    function getMonthForSalary() {
        $month = $this->session->userdata('cmbMonth');
        $year = $this->session->userdata('cmbYear');
        if ($month && $year) {
            $maxDate = strtotime($year . '-' . $month . '-01 00:00:00');
        } else {
            $condition = array(
                'select' => 'MAX(Date) as MaxDate',
                'disable_del' => TRUE,
            );
            $result = $this->selectDB($this->table_timecard, $condition);
            if (count($result) && !empty($result[0]->MaxDate)) {
                $maxDateString = $result[0]->MaxDate;
                $maxDates = strtotime($maxDateString);
                $maxDate = strtotime(date('Y-m-1 00:00:00', $maxDates));
            } else {
                $maxDate = strtotime(date('Y-m-1 00:00:00'), time());
            }
            $tempData = array(
                'cmbMonth' => date('m', $maxDate),
                'cmbYear' => date('Y', $maxDate),
            );
            $this->session->set_userdata($tempData);
        }
        return $maxDate;
    }

    /*
     * @author :        Quyet
     * @created:        20/6/2014
     * @Description:    Update table database
     * @Input :         (String) $table table name
     *                  (Array) $data data for insert or update table
     *                  (Array) $condition condition
     * @Output :        Integer/FALSE
     */

    function updateDB($table = '', $data = array(), $condition = array()) {
        if (empty($table) || empty($data)) {
            $temp = FALSE;
        } else {
            $this->db->trans_begin();
            if (count($condition)) {
                /* update database */
                foreach ($condition as $key => $value) {
                    $this->db->where($key, $value);
                }
                /* BEGIN update 8/12/2014 */
                $data['Upd_ID'] = $this->session->userdata('UserId');
                $data['Upd_Date'] = date('Y-m-d H:i:s');
                /* END update 8/12/2014 */
                $this->db->update($table, $data);
            } else {
                /* insert database */
                /* BEGIN update 8/12/2014 */
                $data['Ins_ID'] = $this->session->userdata('UserId');
                $data['Ins_Date'] = date('Y-m-d H:i:s');
                $data['Upd_ID'] = $this->session->userdata('UserId');
                $data['Upd_Date'] = date('Y-m-d H:i:s');
                /* END update 8/12/2014 */
                $this->db->insert($table, $data);
            }
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $temp = FALSE;
            } else {
                $this->db->trans_commit();
                $temp = TRUE;
            }
        }
        return $temp;
    }

    /*
     * @author :        Quyet
     * @created:        20/6/2014
     * @Description:    set date 
     * @Input :         (String) $string
     *                  (String) $format
     * @Output :        String
     */

    function setDate($string = '', $format = 'Y/m/d') {
        if ($string == '' || $string == '0000-00-00') {
            return FALSE;
        } else {
            return date($format, strtotime($string));
        }
    }

    /*
     * @author :        Quyet
     * @created:        25/6/2014
     * @Description:    is duplicate record
     * @Input :         (String) $table
     *                  (Array) $condition
     * @Output :        object/false
     */

    function checkDuplicate($table = '', $condition = array()) {
        if (!empty($table) && count($condition)) {
            $this->db->where($condition);
            $count = $this->db->count_all_results($table);
            if ($count) {
                return TRUE;
            }
        } else {
            return FALSE;
        }
    }

    /*
     * @author :        Quyet
     * @created:        1/7/2014
     * @Description:    set date 
     * @Input :         (String) $table
     *                  (Array) $condition
     * @Output :        String
     */

    function deleteDB($table = '', $condition = array()) {
        if (empty($table)) {
            $temp = FALSE;
        } else {
            $this->db->trans_begin();
            if (count($condition)) {
                /* update database */
                foreach ($condition as $key => $value) {
                    $this->db->where($key, $value);
                }
            }
            $this->db->delete($table);
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $temp = FALSE;
            } else {
                $this->db->trans_commit();
                $temp = TRUE;
            }
        }
        return $temp;
    }

    /*
     * @author :        Quyet
     * @created:        12/8/2014
     * @Description:    select common
     * @Input :         $condition = array(
     *                      'select' => [String],
     *                      'join' => array(
     *                                  array('table'=>$table[String], 'condition'=> $condition[String], 'type'=> $type[String]),
     *                                  array('table'=>$table[String], 'condition'=> $condition[String], 'type'=> $type[String]),
     *                                )
     *                      'where' => [array], [String]],
     *                      'or_where' => [[array], [String]],
     *                      'where_in' => array($filed => array()),
     *                      'or_where_in' => array($filed => array()),
     *                      'where_not_in' => array($filed => array()),
     *                      'or_where_not_in' => array($filed => array()),
     *                      'like' => array($field => $value),
     *                      'or_like' => array($field => $value),
     *                      'not_like' => array($field => $value),
     *                      'or_not_like' => array($field => $value),
     *                      'group_by' => [array],
     *                      'distinct' => [bolean],
     *                      'having' => [array], [String]],
     *                      'or_having' => [array], [String]],
     *                      'order_by' => [String],
     *                      'limit' => [array],
     *                      'first' => [boolean], //the true return first record
     *                      'disable_del' => [boolean], //if true, it is not query with del_falg
     *                      'count' => [boolean], //if true, it is not query with del_falg
     *                  )
     * @Output :        array()/FALSE
     */

    function selectDB($table = '', $condition = array()) {
        $temp = FALSE;
        if ($table) {
            $this->db->from($table);
            if (count($condition)) {
                /* set condition group A */
                $listKeyA = array('select', 'where', 'or_where', 'group_by', 'having', 'or_having', 'order_by');
                foreach ($listKeyA as $item) {
                    if (isset($condition[$item])) {
                        $this->db->$item($condition[$item]);
                    }
                }
                /* set join table */
                if (isset($condition['join']) && is_array($condition['join']) && count($condition['join'])) {
                    foreach ($condition['join'] as $item) {
                        $this->db->join($item['table'], $item['condition'], $item['type']);
                    }
                }
                /* set condition group B */
                $listKeyB = array('where_in', 'or_where_in', 'where_not_in', 'or_where_not_in');
                foreach ($listKeyB as $item) {
                    if (isset($condition[$item]) && is_array($condition[$item]) && count($condition[$item])) {
                        foreach ($condition[$item] as $key => $item_) {
                            $this->db->$item($key, $item_);
                        }
                    }
                }
                /* set condition group C */
                $listKeyC = array('like', 'or_like', 'not_like', 'or_not_like',);
                foreach ($listKeyC as $item) {
                    if (isset($condition[$item]) && is_array($condition[$item]) && count($condition[$item])) {
                        $this->db->$item($condition[$item]);
                    }
                }
                /* set distinct table */
                if (isset($condition['distinct']) && $condition['distinct'] == TRUE) {
                    $this->db->distinct();
                }
                /* set limit table */
                if (isset($condition['limit']) && is_array($condition['limit'])) {
                    if (count($condition['limit']) == 1) {
                        $this->db->limit($condition['limit'][0]);
                    } elseif (count($condition['limit']) == 2) {
                        $this->db->limit($condition['limit'][1], $condition['limit'][0]);
                    }
                }
            }
            $lever = $this->session->userdata('Level');
            if (isset($condition['disable_del']) && $condition['disable_del'] == TRUE) {
                // No query with Del_Flag
            } elseif ($lever == 1) {
                // Query with All Del_Flag Status
            } elseif ($lever == 2) {
                // Query with Del_Flag Status = 0
                $this->db->where('Del_Flag', 0);
            }
            if (isset($condition['count']) && $condition['count'] == TRUE) {
                $temp = $this->db->count_all_results();
            } else {
                $query = $this->db->get();
                $temp = $query->result();
                if (isset($condition['first']) && $condition['first'] == TRUE && isset($temp[0])) {
                    $temp = $temp[0];
                }
            }
        }
        return $temp;
    }

    /*
     * @author :        Quyet
     * @created:        12/8/2014
     * @Description:    count result
     * @Input :         (String) $table
     *                  (array) $condition
     * @Output :        Interger
     */

    function countResult($table = '', $condition = array()) {
        $temp = 0;
        if ($table) {
            $this->db->from($table);
            if (is_array($condition) && count($condition)) {
                $this->db->where($condition);
            }
            $lever = $this->session->userdata('Level');
            if ($lever == 1) {
                // Query with All Del_Flag Status
            } elseif ($lever == 2) {
                // Query with Del_Flag Status = 0
                $this->db->where('Del_Flag', 0);
            }
            $temp = $this->db->count_all_results();
        }
        return $temp;
    }

    /*
     * @author :        Quyet
     * @created:        20/6/2014
     * @Description:    Insert or update batch
     * @Input :         (String) $table table name
     *                  (Array) $data data for insert or update table
     * @Output :        Boolean
     */

    function updateBatchDB($table = '', $data = array(), $fieldKey = '') {
        if (empty($table) || empty($data)) {
            $temp = FALSE;
        } else {
            $this->db->trans_begin();
            if (empty($fieldKey)) {
                $this->db->insert_batch($table, $data);
            } else {
                $this->db->update_batch($table, $data, $fieldKey);
            }
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $temp = FALSE;
            } else {
                $this->db->trans_commit();
                $temp = TRUE;
            }
        }
        return $temp;
    }

}

?>